# -*- coding: utf8  -*-

import os
import sys
import datetime
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders

def save_packages(packages_file):
	# Volcamos en el fichero el nombre de todos los paquetes instalados
	comando = 'dpkg --get-selections | grep -v deinstall > ' + packages_file
	os.system(comando)

def save_sources(sources_file):
	# Copiamos el fichero sources.list con la lista de los repositorios
	comando = 'cp /etc/apt/sources.list ' + sources_file
	os.system(comando)
	
def restore_sources(sources_file):
	# Restauramos el fichero sources.list
	comando = 'gksudo mv ' + sources_file + ' /etc/apt/sources.list'
	os.system(comando)
	# Hacemos update
	comando = 'gksudo sudo apt-get update'
	os.system(comando)
	
def restore_packages(packages_file):
	# Restauramos los paquetes
	comando = 'gksudo dpkg --set-selections < ' + packages_file
	os.system(comando)
	
def email_backup(user, password, attach_list, smtp_server):
	today = datetime.datetime.now()

	msg = MIMEMultipart()

	msg['From'] = user
	msg['To'] = user
	msg['Subject'] = 'Packages backup for ' + str(today)
	body = "Backup generated by 'Tiny Backup 0.1'"

	msg.attach(MIMEText(body))

	for attachment in attach_list:
		part = MIMEBase('application', 'octet-stream')
		part.set_payload(open(attachment, 'rb').read())
		Encoders.encode_base64(part)
		part.add_header('Content-Disposition', 'attachment; filename="%s"' % attachment)
		msg.attach(part)

	mailServer = smtplib.SMTP(smtp_server, 587)
	mailServer.ehlo()
	mailServer.starttls()
	mailServer.ehlo()
	mailServer.login(user, password)
	mailServer.sendmail(user, user, msg.as_string())
	mailServer.close()
